package com.example.demo.utils;

import java.io.IOException;
import java.net.*;
import java.util.Scanner;

public class UDPUtil {
    public void send() throws IOException {
        DatagramSocket socket = new DatagramSocket();//创建UDP对象
        Scanner sc = new Scanner(System.in);//创建用户输入器
        while (true) {
            String msg = sc.nextLine();//用户输入
            if(msg.equals("exit")){
                System.out.println("退出");
                break;
            }
            byte[] buf = msg.getBytes();
            //构造发送包内容和发送地址
            DatagramPacket packet = new DatagramPacket(buf, buf.length, InetAddress.getLocalHost(), 6666);
            socket.send(packet);//发送
            System.out.println("发送完毕");
        }
        socket.close();
    }

    public void receive() throws IOException{
        DatagramSocket socket = new DatagramSocket(6666);//创建UDP对象，设置监听端口
        //设置接收信息缓冲区
        byte[] buf = new byte[1024*64];
        DatagramPacket packet = new DatagramPacket(buf, buf.length);
        while (true) {
            socket.receive(packet);//接收信息
            int len = packet.getLength();
            String rs = new String(buf,0,len);//获取信息
            System.out.println(rs);
            System.out.println(packet.getAddress());
            System.out.println(packet.getPort());
            System.out.println("-------");
        }
        //socket.close();
    }
}
